import { PokerPoints } from "../constant/PokerPoints"
import { PokerSuits } from "../constant/PokerSuits"
import { Poker } from "../data/Poker"
import ArrayUtil from "../utils/ArrayUtil"
import RandomUtil from "../utils/RandomUtil"

/**
 * 扑克牌管理类
 */
export default class PokerManager {
  private static _instance: PokerManager = null!

  // 单例
  public static get instance(): PokerManager {
    if (this._instance == null) {
      this._instance = new PokerManager()
    }
    return this._instance
  }

  private constructor() { }

  // 获取一副牌
  public getDeck(): Poker[] {
    let cards: Array<Poker> = []
    // 花色
    // SPADE = 3,    // 黑桃♠
    // HEARD = 2,    // 红桃♥
    // CLUB = 1,     // 梅花♣
    // DIAMOND = 0,  // 方块♦
    const suits = [PokerSuits.DIAMOND, PokerSuits.CLUB, PokerSuits.HEARD, PokerSuits.SPADE]
    // 牌值
    // P_A = 1,
    // P_2 = 2,
    // P_3 = 3,
    // P_4 = 4,
    // P_5 = 5,
    // P_6 = 6,
    // P_7 = 7,
    // P_8 = 8,
    // P_9 = 9,
    // P_10 = 10,
    // P_J = 11,    // 王子
    // P_Q = 12,    // 皇后
    // P_K = 13,    // 国王
    // P_BJ = 14,   // 小王 black joker
    // P_RJ = 15,   // 大王 red joker
    const points = [
      PokerPoints.P_A, PokerPoints.P_2, PokerPoints.P_3, PokerPoints.P_4, PokerPoints.P_5,
      PokerPoints.P_6, PokerPoints.P_7, PokerPoints.P_8, PokerPoints.P_9, PokerPoints.P_10,
      PokerPoints.P_J, PokerPoints.P_Q, PokerPoints.P_K
    ]

    suits.forEach(suit => {
      points.forEach(point => {
        cards.push(new Poker({ suit, point }))
      })
    })

    // 大小王
    cards.push(new Poker({
      suit: PokerSuits.NONE,
      point: PokerPoints.P_RJ
    }))
    cards.push(new Poker({
      suit: PokerSuits.NONE,
      point: PokerPoints.P_BJ
    }))

    // 洗牌
    this.shuffle(cards)

    return cards
  }

  /**
   * 洗牌
   * @param cards 
   */
  public shuffle(cards: Poker[]) {
    // 两两随机交换
    for (let i = 0; i < cards.length; i++) {
      const i1 = RandomUtil.getRangeInt(0, cards.length)
      const i2 = RandomUtil.getRangeInt(0, cards.length)
      // 交换
      ArrayUtil.swap(cards, i1, i2)
    }
  }
}